package com.dongdongshop.filter;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dongdongshop.data.Result;
import com.dongdongshop.enums.ResultEnum;
import com.dongdongshop.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Set;

@Component//实例化
@RefreshScope//随配置文件随时改变的
public class TokenFilter implements GlobalFilter, Ordered {
    @Autowired
    private JwtUtil jwtUtil;

    @Value("#{'${gateway.exclusions.url}'.empty ? null : '${gateway.exclusions.url}'.split(',')}")
    private Set<String> urls;

    private PathMatcher pathMatcher = new AntPathMatcher();

    //过滤器功能
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //取出token
        ServerHttpRequest request = exchange.getRequest();
        //获取当前路径
        String path = request.getURI().getPath();
        //判断路路径是否需要效验
        for (String url : urls) {
            boolean match = pathMatcher.match(url, path);
            if (match) {
                return chain.filter(exchange);
            }
        }
        String token = request.getHeaders().getFirst("AutharizeToken");
        //如果token不存在就是无效的token
        if (token == null || "".equals(token)) {
            return   response(exchange);
        }
        //如果token存在,就需要效验token是否合法,如果解析不出来就会抛出异常
        try {
            jwtUtil.parseJwt(token);
        } catch (Exception e) {
            return response(exchange);
        }
        return chain.filter(exchange);
    }

    //封装token无效的方法
    private Mono<Void> response(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        //这里在返回头添加编码，否则中文会乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        byte[] bytes = JSONObject.toJSONBytes(Result.RESPOSE(ResultEnum.INVALID_TOKEN), SerializerFeature.WriteMapNullValue);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(buffer));
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
